
IF EXISTS (SELECT 1 FROM sysobjects WHERE type ='RI' AND name='BbReservaLibro_FK_1')
	ALTER TABLE [BbReservaLibro] DROP CONSTRAINT [BbReservaLibro_FK_1];

IF EXISTS (SELECT 1 FROM sysobjects WHERE type ='RI' AND name='BbReservaLibro_FK_2')
	ALTER TABLE [BbReservaLibro] DROP CONSTRAINT [BbReservaLibro_FK_2];

IF EXISTS (SELECT 1 FROM sysobjects WHERE type = 'U' AND name = 'BbReservaLibro')
BEGIN
	 DECLARE @reftable_37 nvarchar(60), @constraintname_37 nvarchar(60)
	 DECLARE refcursor CURSOR FOR
	 select reftables.name tablename, cons.name constraintname
	  from sysobjects tables,
		   sysobjects reftables,
		   sysobjects cons,
		   sysreferences ref
	   where tables.id = ref.rkeyid
		 and cons.id = ref.constid
		 and reftables.id = ref.fkeyid
		 and tables.name = 'BbReservaLibro'
	 OPEN refcursor
	 FETCH NEXT from refcursor into @reftable_37, @constraintname_37
	 while @@FETCH_STATUS = 0
	 BEGIN
	   exec ('alter table '+@reftable_37+' drop constraint '+@constraintname_37)
	   FETCH NEXT from refcursor into @reftable_37, @constraintname_37
	 END
	 CLOSE refcursor
	 DEALLOCATE refcursor
	 DROP TABLE [BbReservaLibro]
END


CREATE TABLE [BbReservaLibro]
(
	[id] INT  NOT NULL IDENTITY,
	[idPersona] INT  NOT NULL,
	[idLibro] INT  NOT NULL,
	[fechaGenera] DATETIME  NOT NULL,
	[fechaVencimiento] DATETIME  NULL,
	[finalizado] INT default 0 NULL,
	CONSTRAINT [BbReservaLibro_PK] PRIMARY KEY ([id])
);

BEGIN
ALTER TABLE [BbReservaLibro] ADD CONSTRAINT [BbReservaLibro_FK_1] FOREIGN KEY ([idPersona]) REFERENCES [BBPersona] ([id]) ON DELETE CASCADE
END
;

BEGIN
ALTER TABLE [BbReservaLibro] ADD CONSTRAINT [BbReservaLibro_FK_2] FOREIGN KEY ([idLibro]) REFERENCES [CTLibro] ([idLibro]) ON DELETE CASCADE
END
;
